package com.celan.year2023.month01.day05;

import java.util.*;

public class Solution {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    List<TreeNode> list = new ArrayList<>();

    public void flatten(TreeNode root) {
        dfs(root);
        for (int i = 1; i < list.size(); i++) {
            TreeNode pre = list.get(i - 1);
            TreeNode cur = list.get(i);
            pre.left = null;
            pre.right = cur;
        }
    }

    private void dfs(TreeNode root) {
        if (root == null) return;

        list.add(root);
        dfs(root.left);
        dfs(root.right);
    }

    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) set.add(num);
        int max = 1;

        for (int num : set) {
            if (!set.contains(num - 1)) {
                int cur = num;
                int length = 1;
                while (set.contains(cur + 1)) {
                    cur++;
                    length++;
                }
                max = Math.max(max, length);
            }
        }
        return max;
    }
}
